package net.lgpage.http;

import java.util.List;
import java.util.Map;

import net.lgpage.http.ExceptionAsyncTask.HttpErrorCodeException;
import net.lgpage.http.ExceptionAsyncTask.HttpMsgPauseException;
import net.lgpage.http.ExceptionAsyncTask.HttpSessionOutTimeException;
import net.lgpage.tool.GsonTool;

public class ServiceUtil {
	
	public static <T> T getObjFromHttpMsg(String appurl,
			Map<String, String> map, Class<T> clazz) throws Exception {
		String res = HttpClientUtil.postAppendUrl(appurl, map);
		HttpMsg msg = checkHttpMsg(res);
		T tmps = null;
		tmps = GsonTool.getGson().fromJson(msg.getObj().toString(), clazz);
		return tmps;
	}

	public static <T> List<T> getListFromHttpMsg(String appurl,
			Map<String, String> map, Class<T> clazz) throws Exception {
		String res = HttpClientUtil.postAppendUrl(appurl, map);
		HttpMsg msg = checkHttpMsg(res);
		System.out.println(msg.getObj().toString());
		//List<T> list = gson.fromJson(msg.getObj(), new TypeToken<List<T>>(){}.getType()); 
		List<T> list = GsonTool.getList(msg.getObj().toString(), clazz);
		return list;
	}

	public static HttpMsg getHttpMsg(String appurl, Map<String, String> map)
			throws Exception {
		String res = HttpClientUtil.postAppendUrl(appurl, map);
		return checkHttpMsg(res);
	}

	
	public static HttpMsg putMap(String appurl, Map<String, String> map)
			throws Exception {
		String res = HttpClientUtil.postAppendUrl(appurl, map);
		return checkHttpMsg(res);
	}

	public static HttpMsg checkHttpMsg(String res) throws Exception {
		HttpMsg msg = GsonTool.getGson().fromJson(res, HttpMsg.class);
		if (msg == null) {
			throw new HttpMsgPauseException();
		} else {
			if (1 == msg.getStatusCode()) {
				return msg;
			} else if(101 == msg.getStatusCode()){
				throw new HttpSessionOutTimeException(msg.getErrmsg());
			}else {
				throw new HttpErrorCodeException(msg.getErrmsg());
			}
		}
	}
	
}
